import { addAppointment } from "@/api/appointment";
import { addOrder } from "@/api/order";
import { listEmployeeByServiceId, updateFavorite } from "@/api/user";
import { useUserStore } from "@/store";
import { View, Image, Text, Picker, BaseEventOrig } from "@tarojs/components";
import Taro, { useRouter } from "@tarojs/taro";
import dayjs from "dayjs";
import { useEffect, useState } from "react";
import { AtActionSheet, AtActionSheetItem, AtButton, AtCard, AtIcon, AtList, AtListItem, AtMessage, AtRate, AtSearchBar, AtTag, AtToast } from "taro-ui";

const ServiceList: React.FC = () => {
  const router = useRouter();

  const userStore = useUserStore();

  const { serviceId, serviceName } = router.params;

  const [searchKeyWords, setSearchKeyWords] = useState<string>('');
  const [employeeList, setEmployeeList] = useState<EmployeeList[]>([]);

  const [showActionSheet, setShowActionSheet] = useState<boolean>(false);
  const [employeeName, setEmployeeName] = useState<string>('');
  const [employeeId, setEmployeeId] = useState<number>();
  const [status, setStatus] = useState<boolean>();

  const [showOrder, setShowOrder] = useState<boolean>(false);
  const [employeePic, setEmployeePic] = useState<string>();
  const [dateSel, setDateSel] = useState<string>(dayjs().format('YYYY-MM-DD'));
  const [timeSel, setTimeSel] = useState<string>(dayjs().format('HH:mm'));

  const [showAppointmentFlag, setShowAppointmentFlag] = useState<boolean>(false);

  const [buttonType, setButtonType] = useState<'ORDER' | 'APPOINTMENT'>();

  // 是否下单或预约成功
  const [isOk, setIsOk] = useState<boolean>(false);

  const fetchEmployeeByServiceId = async () => {
    const { data } = await listEmployeeByServiceId(Number(serviceId));
    setEmployeeList(data);
  }

  useEffect(() => {
    fetchEmployeeByServiceId();
  }, [serviceId])

  const onActionClick = () => {
    console.log(searchKeyWords);
  }

  const handleFavorite = (id: number, sta: boolean) => {
    if (userStore.token) {
      setShowActionSheet(true);
      setEmployeeId(id);
      setStatus(sta);
    }
  }

  const sureFavorite = async () => {
    // console.log(employeeId);
    const data = await updateFavorite(employeeId as number, !status as boolean);
    if (data.code === 200) {
      if (status === false) {
        Taro.atMessage({
          type: "success",
          message: "收藏成功",
          duration: 1000
        })
      } else {
        Taro.atMessage({
          type: "success",
          message: "取消成功",
          duration: 1000
        })
      }
      fetchEmployeeByServiceId();
    }
    setShowActionSheet(false);
  }

  // 去下单
  const toOrder = (e: BaseEventOrig, avatar: string, name: string, id: number) => {
    e.stopPropagation();
    if (userStore.token) {
      setShowOrder(true);
      setShowAppointmentFlag(false);
      setEmployeePic(avatar);
      setEmployeeName(name);
      setEmployeeId(id);
      setButtonType('ORDER');
    } else {
      Taro.atMessage({
        type: "warning",
        message: "请先登陆",
        duration: 1000
      })
    }
  }

  // 去预约
  const toAppointment = (e: BaseEventOrig, avatar: string, name: string, id: number) => {
    e.stopPropagation();
    if (userStore.token) {
      setShowOrder(true);
      setShowAppointmentFlag(true);
      setEmployeePic(avatar);
      setEmployeeName(name);
      setEmployeeId(id);
      setButtonType("APPOINTMENT");
    } else {
      Taro.atMessage({
        type: "warning",
        message: "请先登陆",
        duration: 1000
      })
    }
  }

  const onDateChange = (e: any) => setDateSel(e.target.value);
  const onTimeChange = (e: any) => setTimeSel(e.target.value);

  // 提交
  const submit = async () => {
    // 下单
    const resultTime = `${dateSel} ${timeSel}`;
    const address = userStore.addressList.find(item => item.current)!.address;
    if (buttonType === "ORDER") {

      const data = await addOrder({ serviceId: Number(serviceId), worker: employeeId!, startTime: resultTime, address });
      if (data.code === 200) {
        setShowOrder(false);
        fetchEmployeeByServiceId()
        setIsOk(true);
      }
    } else {

      // 预约
      const data = await addAppointment({ serviceId: Number(serviceId), worker: employeeId!, startTime: resultTime, address });
      if (data.code === 200) {
        setShowOrder(false);
        fetchEmployeeByServiceId()
        setIsOk(true);
      }
    }
  }

  const handleEmployeeInfo = (id: number) => {
    Taro.navigateTo({ url: `/pages/employee-info/index?employeeId=${id}` })
  }

  return (
    <View className='h-full'>
      <AtMessage />

      <View className='text-xl items-center font-semibold flex justify-between px-2'>
        {serviceName}
        <AtSearchBar
          actionName='搜一下'
          value={searchKeyWords}
          onChange={(value) => setSearchKeyWords(value)}
          className='w-2/3'
          onActionClick={onActionClick}
        />
      </View>
      <View className='bg-gray-100 flex flex-col gap-y-2'>
        {
          employeeList.map((item, index) => (
            <AtCard
              renderIcon={
                item.favorite ?
                  <>
                    <AtIcon value='star-2' color='#FFD700' size={18} /><Text className='ml-1 text-xs text-[#6190E8]'>已收藏</Text>
                  </> :
                  <AtIcon value='star' size={18} />
              }
              key={index}
              onClick={() => handleEmployeeInfo(item.id)}
            >
              <View key={index} className='flex justify-evenly p-2 w-full bg-white' onLongPress={() => handleFavorite(item.id, item.favorite)}>
                <Image src={item.avatar} className='h-20 w-20 rounded-md' />

                <View className='flex flex-col px-2 justify-between'>
                  <View className='text-xl'>
                    {item.employeeName}
                    <AtTag className='ml-1' name='gender' circle size='small'>
                      {item.gender ? '女' : '男'}
                    </AtTag>
                  </View>
                  <AtRate
                    size={15}
                    value={item.score}
                  />
                  <View className='text-red-500 font-semibold'>
                    <Text className='text-xs'>
                      <AtIcon value='money' size='15' color='' className='mr-1' />
                      价格:
                    </Text>
                    <Text className='text-sm'>
                      {item.price}元
                    </Text>
                  </View>
                </View>

                <View className='flex flex-col justify-around'>

                  {
                    item.freeTime ?
                      <>
                        <AtButton type='secondary' size='small' onClick={(e: BaseEventOrig) => toAppointment(e, item.avatar, item.employeeName, item.id)}>预约</AtButton>
                        <AtButton type='primary' size='small' onClick={(e: BaseEventOrig) => toOrder(e, item.avatar, item.employeeName, item.id)}>下单</AtButton>
                      </>
                      :
                      <>
                        <View className='text-sm font-bold text-[#6190E8]'>服务中</View>
                      </>
                  }
                </View>

              </View>
            </AtCard>
          ))
        }

        <AtActionSheet isOpened={showActionSheet} onClose={() => setShowActionSheet(false)} cancelText='取消'>
          <AtActionSheetItem className='flex items-center justify-center' onClick={sureFavorite}>
            {
              status
                ?
                <>
                  <AtIcon value='star-2' color='#FFD700' size='18' className='mr-2' /> 取消收藏
                </>
                :
                <>
                  <AtIcon value='star' size='18' className='mr-2' /> 收藏
                </>
            }
          </AtActionSheetItem>
        </AtActionSheet>

        <AtActionSheet isOpened={showOrder} onClose={() => setShowOrder(false)} cancelText='取消'>
          <AtActionSheetItem className='flex items-center justify-center'>
            <View className='flex justify-around w-full items-center'>
              <Image src={employeePic as string} className='w-20 h-20 flex-shrink-0' />
              <View className='w-full flex justify-center items-center flex-col gap-y-2'>

                <View className='w-11/12 flex justify-between items-center'>
                  <View className='text-xs font-semibold text-[#6190E8]'>本次服务员工</View>
                  <View className='text-xl'>{employeeName}</View>
                </View>

                <View className='w-11/12 flex justify-between items-start'>
                  <View className='text-xs font-semibold text-[#6190E8]'>服务时间</View>
                  <View className='flex flex-col justify-start items-start'>
                    {
                      showAppointmentFlag ?
                        <Picker mode='date' value={dateSel} onChange={onDateChange}>
                          <AtList>
                            <AtListItem className='text-xs' title='请选择日期' extraText={dateSel} />
                          </AtList>
                        </Picker>
                        :
                        <></>
                    }
                    <Picker mode='time' value={timeSel} onChange={onTimeChange}>
                      <AtList>
                        <AtListItem className='text-xs' title='请选择时间' extraText={timeSel} />
                      </AtList>
                    </Picker>
                  </View>
                </View>

                <View className='w-11/12 flex justify-between items-center'>
                  <View className='text-xs font-semibold text-[#6190E8]'>当前下单地址</View>
                  <View className='text-sm'>
                    {!!userStore.addressList ? userStore.addressList.find(item => item.current)?.address : ""}
                  </View>
                </View>

              </View>
            </View>
          </AtActionSheetItem>
          <AtActionSheetItem onClick={submit}>
            确定
          </AtActionSheetItem>
        </AtActionSheet>
      </View>

      <AtToast isOpened={isOk} text='成功' status='success' />
    </View>
  )
}
export default ServiceList;
